<template>
	<view class="page publishpage" @touchstart="touchStart" @touchend="touchEnd">
		<form>
			<view class="uni-textarea">
				<textarea placeholder="这一刻的想法..." v-model="input_content" />
			</view>
			<view class="uni-list list-pd">
				<view class="uni-list-cell cell-pd">
					<view class="uni-uploader">
						<view class="uni-uploader-head">
							<view class="uni-uploader-title"></view>
							<view class="uni-uploader-info">{{imageList.length}}/9</view>
						</view>
						<view class="uni-uploader-body">
							<view class="uni-uploader__files">
								<block v-for="(image,index) in imageList" :key="index">
									<view class="uni-uploader__file" style="position: relative;">
										<image class="uni-uploader__img" mode="aspectFill" :src="photo_cdn+image" :data-src="photo_cdn+image" @tap="previewImage(imageList,index)"></image>
										<view class="close-view" @click="close(index)">×</view>
									</view>
								</block>
								<view class="uni-uploader__input-box" v-show="imageList.length < 9">
									<view class="uni-uploader__input" @tap="chooseImage()"></view>
								</view>
							</view>
						</view>
					</view>
				</view>
			</view>
			
			<!-- <view class="uni-list list-pd">
				<view class="uni-list-cell cell-pd">
					<view class="uni-uploader">
						<view class="uni-uploader-body">
							<view class="uni-uploader__files">
								<block v-for="(video,index) in videoList" :key="index">
									<view class="uni-uploader__file" style="position: relative;">
										<video ></video>
										<view class="close-view" @click="close(index)">×</view>
									</view>
								</block>
								<view class="uni-uploader__input-box">
									<view class="uni-uploader__input" @tap="chooseVideo()"></view>
								</view>
							</view>
						</view>
					</view>
				</view>
			</view> -->
			
			<view class="accordtag">
				<view class="radioview">
					<radio @tap="radioChange" :checked="isAgree" :color="$themecolor" />已阅读并同意
					<text @tap="totreaty" class="atag">《用户协议》</text>
					用户协议中关于发布族志和圈子的说明策略
				</view>
				
			</view>
			
			<view class="footer">
				<view class="feedsubmit" @tap="publish">提交</view>
			</view>
		</form>
		<login :hidden="isshowlogin" @close="closefun" @loginsucc="loginsucc"></login>
	</view>
</template>

<script>
	import image from '@/common/image.js';
	import {addFriendShip} from '@/utils/api/user.js';
	import config from "@/utils/config.js";
	import {lk_reverse} from "@/utils/libs/luokuangmap.js";
	let {uploadFile,photo_cdn} = config.baseUrl;
	var sourceType = [
		['camera'],
		['album']
	]
	var sizeType = [
		['compressed'],
		['original'],
		['compressed', 'original']
	]
	export default {
		data() {
			return {
				isAgree:false,
				input_content:'',
				imageList: [],//照片
				videoList: [],//视频
				photo_cdn,
				province_id:'',
				isshowlogin: false,
				
				// sizeTypeIndex: 2,
				// sizeType: ['压缩', '原图', '压缩或原图'],
				countIndex: 8,
				count: [1, 2, 3, 4, 5, 6, 7, 8, 9],
				
				//侧滑返回start
				startX: 0, //点击屏幕起始位置
				movedX: 0, //横向移动的距离
				endX: 0, //接触屏幕后移开时的位置
				//end
			}
		},
		onShow(){
			let token = uni.getStorageSync("token")
			if(!token){
				// #ifdef MP-WEIXIN
				setTimeout(() => {
					this.isshowlogin = true;
				}, 1500)
				// #endif
			}
			//取缓存的省份id
			let province_id = uni.getStorageSync("province_id");
			if(province_id){
				this.province_id = province_id;
			}
		},
		onUnload() {
			this.imageList = [],
			this.countIndex = 8;
		},
		
		methods: {
			//单选框
			radioChange(e){
				this.isAgree = !this.isAgree;
			},
			//用户协议
			totreaty(){
				uni.navigateTo({
					url:"/pages/mine/agreement/agreementuser"
				})
			},
			async publish(){
				
				if(!this.isAgree){
					this.$api.msg("请阅读并同意用户协议!");
					return false;
				}
				
				let picture_arr = this.imageList.map((item,index)=>{return item});
				let picture_arr_two = picture_arr.filter(item=> item!="" && item!=undefined &&  item)
				let picture_str = picture_arr_two.join(",");
				console.log(picture_str,'picture_str')
				if (!this.input_content) {
					uni.showModal({ content: '内容不能为空', showCancel: false, });
					return;
				}
				let token = uni.getStorageSync("token");
				// if(token && !this.province_id){
				// 	this.getlatandlng_one();
				// }			
				let res = await addFriendShip({
					content:this.input_content,
					pics:picture_str,
					province_id:this.province_id
				})
				this.$api.msg(res.msg);
				if(res.code==1){					
					//记录需要刷新的状态
					uni.setStorageSync("set_load",1);					
					setTimeout(()=>{
						uni.navigateBack()
					},1000)					
				}				
			},	
			close(e){
			    this.imageList.splice(e,1);
			},
			//上传照片
			chooseImage: async function(index) {
				if (this.imageList.length === 9) {
					let isContinue = await this.isFullImg();
					console.log("是否继续?", isContinue);
					if (!isContinue) {
						return;
					}
				}
				console.log(index,'index')
				uni.chooseImage({
					sourceType:['album','camera'],//album 从相册选图，camera 使用相机
					// sizeType: sizeType[this.sizeTypeIndex],
					count: this.imageList.length + this.count[this.countIndex] > 9 ? 9 - this.imageList.length : this.count[this.countIndex],
					success: (e) => {
						const tempFilePaths = e.tempFilePaths;
						for(let i=0;i<tempFilePaths.length;i++){
							let tempFilePaths_item  = tempFilePaths[i];
							uni.uploadFile({
							    url: uploadFile, 
							    filePath: tempFilePaths_item,
							    name: 'file',
								header:{
									'token':uni.getStorageSync("token"),
								},
							    formData: {
							       "Content-Type": "multipart/form-data",
							       water: 0
							    },
							    success: (res) => {
									let {data} = JSON.parse(res.data)
									console.log('多选',data);
									let ress = JSON.parse(res.data);
									if(ress.code==1){
										this.imageList.push(ress.data.url)
									}
							    },
								fail: (err) => {
									this.$api.msg("上传图片失败");
								}
							});
						}
						
						// // #ifdef APP-PLUS
						// //提交压缩,因为使用了H5+ Api,所以自定义压缩目前仅支持APP平台
						// var compressd = cp_images=> {
						// 	this.imageList = this.imageList.concat(cp_images)//压缩后的图片路径
						// }
						// image.compress(e.tempFilePaths,compressd);
						// // #endif
						
						// // #ifndef APP-PLUS
						// this.imageList = this.imageList.concat(e.tempFilePaths)//非APP平台不支持自定义压缩,暂时没有处理,可通过uni-app上传组件的sizeType属性压缩
						// // #endif
						// console.log(this.imageList)
					}
				})
			},
			//上传视频
			chooseVideo: async function(index){
				uni.chooseVideo({
					sourceType: ['album', 'camera'], 
					success: function(res){
						if(res.size > 20971520){
							this.$api.msg('视频文件过大')
							return false;
						}
						console.log(res.tempFilePath,'res')
						uni.uploadFile({
						    url: uploadFile, 
						    filePath: res.tempFilePath,
						    name: 'file',
							header:{
								'token':uni.getStorageSync("token"),
							},
						    formData: {
						       "Content-Type": "multipart/form-data",
						       water: 0
						    },
						    success: (res) => {
								let {data} = JSON.parse(res.data)
								let ress = JSON.parse(res.data);
								if(ress.code==1){
									this.videoList.push(ress.data.url)
									console.log(this.videoList,'this.videoList')
								}
						    },
							fail: (err) => {
								this.$api.msg("上传视频失败");
							}
						});					
					}
				})
			},
			isFullImg: function() {
				return new Promise((res) => {
					uni.showModal({
						content: "已经有9张图片了,是否清空现有图片？",
						success: (e) => {
							if (e.confirm) {
								this.imageList = [];
								res(true);
							} else {
								res(false)
							}
						},
						fail: () => {
							res(false)
						}
					})
				})
			},
			previewImage(imageList,index) {
				let urls = imageList.map((item)=>{
					return this.photo_cdn + item;
				})
				uni.previewImage({
					current: index,
					urls: urls
				})
			},
			touchStart: function(e) {
				this.startX = e.mp.changedTouches[0].pageX;
			},
			
			touchEnd: function(e) {
				this.endX = e.mp.changedTouches[0].pageX;
				if (this.endX - this.startX > 200) {
					uni.navigateBack();
				}
			},
			//关闭授权登录弹窗
			closefun() {
				this.isshowlogin = false;
			},
			loginsucc(){
				
			},
			//获取定位
			getlatandlng_one(){
				let istongyilat = uni.getStorageSync("istongyilat");
				if(istongyilat==1){
					this.getlatandlng();
				}else if(istongyilat==2){
					console.info("被拒绝了 不再询问！！");
				}
				else{
					// delCancel: true,
					if(uni.getSystemInfoSync().platform=='ios'){
						this.$showModal({
						    title:'温馨提示',
						    concent:'系统将获取您的位置信息,用于展示您发帖的地址',
						    confirmVal:'继续',
							delCancel:true,
						    // cancelVal:'拒绝',
						}).then(res=>{
							uni.setStorageSync("istongyilat",1)
						    this.getlatandlng();
						}).catch(()=>{
						   //拒绝了~~
						   //拒绝了
						   uni.setStorageSync("istongyilat",2);
						})
					}else{
						this.$showModal({
						    title:'温馨提示',
						    concent:'系统将获取您的位置信息,用于展示你的评论位置 是否继续？',
						    confirmVal:'继续',
						    cancelVal:'拒绝',
						}).then(res=>{
							uni.setStorageSync("istongyilat",1)
						    this.getlatandlng();
						}).catch(()=>{
						   //拒绝了~~
						   //拒绝了
						   uni.setStorageSync("istongyilat",2);
						})
					}
				}
			},
			getlatandlng(){
				// #ifndef MP-WEIXIN
				uni.getLocation({
					// type: 'gcj02', //返回可以用于uni.openLocation的经纬度
					success: res => {
						this.latitude = res.latitude;
						this.longitude = res.longitude;
						this.lk_reverse_fun({lon:res.longitude,lat:res.latitude});
					},
					fail: err => {
						console.info("err",err);
					}
				})
				// #endif
			
				// #ifdef MP-WEIXIN
				uni.getFuzzyLocation({
					type: 'gcj02', //返回可以用于uni.openLocation的经纬度
					success: res => {
						this.latitude = res.latitude;
						this.longitude = res.longitude;
						this.lk_reverse_fun({lon:res.longitude,lat:res.latitude});
					},
					fail: err => {
						console.info("err",err);
					}
				})
				// #endif
			},
			//逆解析
			lk_reverse_fun(res){
				lk_reverse({
					lon:res.lon,
					lat:res.lat,
				}).then((success)=>{
					console.info('success',success);
					let result = success.result[0];
					console.info("province_id",result.properties.province_id,typeof(result.properties.province_id));
					this.province_id = result.properties.province_id;
					uni.getStorageSync("province_id",this.province_id);
					
					uni.getStorageSync("county_id",result.properties.county_id);
					// this.district = result.properties.county;
					// let county_id = parseInt(result.properties.county_id);
					// this.city_id = county_id-(county_id%100);
				})
			},
		}
	}
</script>

<style lang="scss">
@import "./publish.scss"

</style>
